package com.ruoyi.game.controller;


import cn.shuibo.annotation.Decrypt;
import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.bean.marketing.transfer.PartnerTransferRequest;
import com.github.binarywang.wxpay.bean.marketing.transfer.PartnerTransferResult;
import com.github.binarywang.wxpay.bean.merchanttransfer.TransferCreateRequest;
import com.github.binarywang.wxpay.bean.transfer.TransferBatchesRequest;
import com.github.binarywang.wxpay.bean.transfer.TransferBatchesResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.PartnerTransferService;
import com.github.binarywang.wxpay.service.TransferService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.TransferServiceImpl;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.WxPayUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.game.domain.GameUser;
import com.ruoyi.game.domain.GameUserConfig;
import com.ruoyi.game.domain.GameWithdrawalRecord;
import com.ruoyi.game.service.IGameConfigService;
import com.ruoyi.game.service.IGameUserConfigService;
import com.ruoyi.game.service.IGameUserService;
import com.ruoyi.game.service.IGameWithdrawalRecordService;
import com.ruoyi.game.utils.ValidateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 游戏用户自定义Controller
 *
 * @author ruoyi
 * @date 2024-03-17
 */
@RestController
@RequestMapping("/api/user")
public class CustomGameUserController extends BaseController {

    @Autowired
    private IGameUserService gameUserService;
    @Autowired
    private ValidateTime validateTime;
    @Autowired
    private IGameConfigService iGameConfigService;

    @Autowired
    private IGameWithdrawalRecordService iGameWithdrawalRecordService;

    @Autowired
    private IGameUserConfigService iGameUserConfigService;



    /*
    添加APP用户
    接收JSON数据
    */

    @Decrypt
    @PostMapping("/adUser")
    public AjaxResult addUser(@RequestBody JSONObject json) {
        String timestamp = json.getString("timestamp");
        //时间戳验证
        if (!validateTime.validateTime(timestamp)) {
            return error();
        } else {
            //验证成功执行逻辑
            GameUser gameUser = new GameUser();
            gameUser.setUserName(json.getString("userName"));
            gameUser.setUserWxId(json.getString("wxId"));
            gameUser.setUserIp(json.getString("userIp"));
            gameUser.setUserDeviceId(json.getString("userDeviceId"));
            //用户余额
            gameUser.setUserMoney(BigDecimal.ZERO);
            //用户状态
            gameUser.setUserType(0L);

            //用户比例默认为0
            gameUser.setUserProportion(BigDecimal.valueOf(iGameConfigService.selectGameConfigByGame().getGameUserDividends()));
            //用户设备信息
            gameUser.setUserDeviceInfo(json.getString("userDeviceInfo"));
            gameUser.setUserCreationTime(DateUtils.getNowDate());
            gameUser.setUserUpdateTime(DateUtils.getNowDate());
            //添加用户
            gameUserService.insertGameUserByApp(gameUser);
            //设置用户每日默认提现看视频次数
            GameUserConfig gameUserConfig = new GameUserConfig();
            gameUserConfig.setUserId(gameUser.getUserId());
            gameUserConfig.setAdTotal(60L);
            gameUserConfig.setWidthTotal(1L);
            gameUserConfig.setAdTotalReady(0L);
            gameUserConfig.setWidthTotalReady(0L);
            gameUserConfig.setAdIs(0);
            gameUserConfig.setWidthIs(0);
            gameUserConfig.setCreationTime(DateUtils.getNowDate());
            iGameUserConfigService.insertGameUserConfig(gameUserConfig);
            return success(gameUser);
        }
    }

    /**
     * 查询用户
     *
     * @param json json
     * @return 返回用户数据
     */


    @Decrypt
    @PostMapping("/getUser")
    public AjaxResult getUser(@RequestBody JSONObject json) {
        String wxId = json.getString("wxId");
        String timestamp = json.getString("timestamp");
        //时间戳验证
        if (validateTime.validateTime(timestamp)) {
            GameUser gameUser = gameUserService.selectGameUserByWxId(wxId);
            if (gameUser == null){
                return AjaxResult.error(101,"用户未注册！");
            }else{
                return success(gameUser);
            }

        } else {
            return error();
        }

    }

    /**
     * 用户申请提现
     * @param json 数据
     * @return 返回
     */
    @Decrypt
    @RepeatSubmit
    @PostMapping("/userWithdrawal")
    public AjaxResult userWithdrawal(@RequestBody JSONObject json){
        String timestamp = json.getString("timestamp");
        if (!validateTime.validateTime(timestamp)) {
            return AjaxResult.error(105,"异常请求");
        }
        String userId = json.getString("userId");
        BigDecimal withdrawalMoney = BigDecimal.valueOf(json.getLong("withdrawalMoney"));
        Integer channel = json.getInteger("channel");
        GameUser gameUser = gameUserService.selectGameUserByUserId(Long.valueOf(userId));
        if(gameUser == null){
            return AjaxResult.error(101,"该用户不存在");
        }

        //判断今天是否还可以提现
        GameUserConfig gameUserConfig = iGameUserConfigService.selectGameUserConfigByUserId(gameUser.getUserId());
        //总提次数
        Long WidthTotal = gameUserConfig.getWidthTotal();
        //已提次数
        Long WidthTotalReady = gameUserConfig.getWidthTotalReady();

        if(WidthTotalReady>=WidthTotal){

            //已经没有奖励了 开始拒绝
            return AjaxResult.error(101,"今日提现发放已达上限");
        }else{
            WidthTotalReady += 1;
            //提现次数+1
            gameUserConfig.setWidthTotalReady(WidthTotalReady);
        }

        //判断剩余次数
        long widthTotalSurplus = WidthTotal - WidthTotalReady;

        if(widthTotalSurplus == 0){
            //设置为假
            gameUserConfig.setWidthIs(1);
        }



        //更新数据库
        iGameUserConfigService.updateGameUserConfig(gameUserConfig);


        try {
            String userWxId = gameUser.getUserWxId();
            String userName = gameUser.getUserName();
            GameWithdrawalRecord gameWithdrawalRecord = new GameWithdrawalRecord();
            gameWithdrawalRecord.setUserWithdrawalMoney(withdrawalMoney);
            //提现渠道 0微信 1支付宝
            gameWithdrawalRecord.setChannel(channel);
            gameWithdrawalRecord.setUserId(Long.valueOf(userId));
            // 0 已发放 1 带审核 2 已拒绝
            gameWithdrawalRecord.setType(1);
            gameWithdrawalRecord.setUserOpenId(userWxId);
            gameWithdrawalRecord.setUserName(userName);
            gameWithdrawalRecord.setCreationTime(DateUtils.getNowDate());
            //先判断用户余额够不够用如果不够用就 暂时扣除用户余额 如果未通过则进行返还
            BigDecimal userMoney = gameUser.getUserMoney();
            BigDecimal subtract = userMoney.subtract(withdrawalMoney);
            System.out.println("提现金额" + withdrawalMoney);
            System.out.println("用户余额" + userMoney);
            System.out.println("扣除提现金额后的金额" +subtract);
            if(userMoney.compareTo(withdrawalMoney) < 0){
                return AjaxResult.error(102,"提现失败金额不够");
            }
            //金额足够则进行计算
            userMoney = subtract.divide(BigDecimal.valueOf(100),2, RoundingMode.HALF_UP);
            System.out.println("用户剩余" +userMoney);
            gameUser.setUserMoney(subtract);
            //更新用户余额
            gameUserService.updateGameUser(gameUser);
            //插入提现记录
            iGameWithdrawalRecordService.insertGameWithdrawalRecord(gameWithdrawalRecord);
        } catch (NumberFormatException e) {
            System.out.println(e.toString());
            return AjaxResult.error(103,"系统错误,请联系管理员");
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("userMoney",gameUser.getUserMoney());
        //剩余提现次数
        stringObjectHashMap.put("WidthTotalReady",widthTotalSurplus);
        return AjaxResult.success(stringObjectHashMap);
    }



    /**
     * 用户提现记录查询
     * @param json 数据
     * @return 返回
     */
    @Decrypt
    @PostMapping("/userWithdrawalRecord")
    public AjaxResult userWithdrawalRecord(@RequestBody JSONObject json){
        String userId = json.getString("userId");
        String timestamp = json.getString("timestamp");
        if (!validateTime.validateTime(timestamp)) {
            return AjaxResult.error(102,"异常请求");
        }
        GameWithdrawalRecord gameWithdrawalRecord = new GameWithdrawalRecord();
        gameWithdrawalRecord.setUserId(Long.valueOf(userId));
        return AjaxResult.success( iGameWithdrawalRecordService.selectGameWithdrawalRecordList(gameWithdrawalRecord));
    }





}
